//
//  Image.swift
//  HuaYun
//
//  Created by enghou on 2018/11/26.
//  Copyright © 2018 xyxorigation. All rights reserved.
//

extension UIImage {
    func drawTextInImage(text: String) -> UIImage {
        // 开启和原图一样大小的上下文（保证图片不模糊的方法）
        UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale)
        // 图形重绘
//        self.draw(in: CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height))
        let attrS = NSMutableAttributedString(string: text, attributes: [NSAttributedString.Key.foregroundColor: UIColor.mainColor, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 8)])
        // 文字属性
        let size =  attrS.size()
        let x = (self.size.width - size.width) / 2
        let y = (self.size.height - size.height) / 2
        
        // 绘制文字
//        self.draw(in: CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height))
        attrS.draw(in: CGRect(x: x, y: y, width: size.width, height: size.height))
        // 从当前上下文获取图片
        let image = UIGraphicsGetImageFromCurrentImageContext()
        //关闭上下文
        UIGraphicsEndImageContext()
        
        return image!
    }
}
